package edu.rpi.tw.escience.stargazer.rest;

import edu.rpi.tw.escience.stargazer.server.SimpleException;
import edu.rpi.tw.escience.stargazer.server.StarGazer;
import edu.rpi.tw.escience.stargazer.server.StarGazerContext;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.restlet.data.MediaType;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;

import java.util.LinkedList;
import java.util.List;

/**
 * Author: josh
 * Date: Apr 27, 2009
 * Time: 11:50:28 PM
 */
public class CelestialObjectResource extends Resource {
    private List<Variant> variants;

    public CelestialObjectResource() {
        //System.out.println("creating resource: " + getRequest().getResourceRef());        
    }

    @Override
    public boolean allowDelete() {
        return false;
    }

    @Override
    public boolean allowGet() {
        return true;
    }

    @Override
    public boolean allowPost() {
        return false;
    }

    @Override
    public boolean allowPut() {
        return false;
    }

    @Override
    public List<Variant> getVariants() {
        if (null == variants) {
            variants = new LinkedList<Variant>();

            variants.add(new Variant(MediaType.APPLICATION_RDF_XML));
            variants.add(new Variant(MediaType.TEXT_HTML));
        }
System.out.println("getting variants for resource: " + getRequest().getResourceRef());
        return variants;
    }

    @Override    
    public Representation represent(final Variant variant) {
        System.out.println("getting representation for resource: " + getRequest().getResourceRef());
        MediaType mt = variant.getMediaType();
        StarGazerContext ctx;
        try {
            ctx = StarGazer.getInstance().getContext();
        } catch (SimpleException e) {
            e.logError();
            return null;
        }

        ValueFactory vf = ctx.getRepository().getValueFactory();
        URI localURI = vf.createURI(getRequest().getResourceRef().toString());
        URI resourceURI = vf.createURI(StarGazer.toStarGazerURI(localURI));

        if (mt.equals(MediaType.APPLICATION_RDF_XML)) {
            return new CelestialObjectRDFRepresentation(resourceURI, ctx);
        } else if (mt.equals(MediaType.TEXT_HTML)) {
            return new CelestialObjectRDFRepresentation(resourceURI, ctx);
//            return new CelestialObjectHTTPRepresentation(resourceURI, ctx, getRequest().getResourceRef().getHostDomain());
        } else {
            new SimpleException("bad media type").logError();

            // FIXME: this may not be safe.
            return null;
        }
    }
}
